/**
 * 
 */
package com.metacube.questionbank.dao;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.SqlLobValue;
import org.springframework.jdbc.support.lob.DefaultLobHandler;
import org.springframework.jdbc.support.lob.LobHandler;
import org.springframework.stereotype.Repository;
import org.springframework.web.multipart.MultipartFile;

import com.metacube.questionbank.jdbc.QuestionRowMapper;
import com.metacube.questionbank.jdbc.UserRowMapper;
import com.metacube.questionbank.model.Question;
import com.metacube.questionbank.model.User;

/**
 * @author Admin39
 *
 */
@Repository
public class UserDAO {
	private static final Logger logger = LoggerFactory.getLogger(UserDAO.class);

	@Autowired
	DataSource dataSource;

	@Autowired
	JdbcTemplate jdbctemplate;

	@PostConstruct
	public void setJdbcTemplate() {
		jdbctemplate.setDataSource(dataSource);

	}

	/*
	 * inserting User in database
	 */
	public boolean insertUser(User user) {
		LobHandler lobHandler = new DefaultLobHandler();

		URL imagepath = UserDAO.class.getClassLoader().getResource(
				"/../../resources/images/defaultImage.jpg");

		logger.info(imagepath + "fullpath");

		File file = new File(imagepath.toExternalForm().substring(6));
		InputStream inputStream = null;
		try {
			inputStream = new FileInputStream(file);
		} catch (FileNotFoundException e) {

		}

		String sql = "INSERT INTO users (email,name, Gender, password,about_me,status,rating,image) VALUES (?,?,?,?,?,?,?,?)";

		logger.info(inputStream + "file length");
		try {
			jdbctemplate.update(
					sql,
					new Object[] {

							user.getEmail(),
							user.getName(),
							user.getGender(),
							user.getPassword(),
							user.getAbout_me(),
							user.getStatus(),
							0,
							new SqlLobValue(inputStream, (int) file.length(),
									lobHandler) }, new int[] { Types.VARCHAR,
							Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
							Types.VARCHAR, Types.INTEGER, Types.INTEGER,
							Types.BLOB });
			return true;
		} catch (Exception e) {
			logger.error("There is a problem in registration");
			return false;
		}
	}

	/*
	 * 
	 * updating the details of user
	 */

	public User updateData(User user, MultipartFile file) {
		String sql = "UPDATE users set  dob=?,gender = ?,about_me=?,status=?,image=?  where user_id = ?";

		InputStream imageIs = null;
		LobHandler lobHandler = new DefaultLobHandler();

		try {
			imageIs = file.getInputStream();
		} catch (IOException e) {

		}
		byte[] byteArr = null;
		try {
			byteArr = file.getBytes();
		} catch (IOException e) {
			e.printStackTrace();
		}

		jdbctemplate.update(sql, new Object[] { user.getDob(),
				user.getGender(), user.getAbout_me(), user.getStatus(),
				new SqlLobValue(imageIs, (int) file.getSize(), lobHandler),
				user.getUser_id() }, new int[] { Types.DATE, Types.VARCHAR,
				Types.VARCHAR, Types.INTEGER, Types.BLOB, Types.INTEGER });

		user = isValidUser(user.getEmail(), user.getPassword());
		return user;
	}

	public User updateData(User user) {
		String sql = "UPDATE users set  dob=?,gender = ?,about_me=?,status=?  where user_id = ?";

		jdbctemplate
				.update(sql,
						new Object[] { user.getDob(), user.getGender(),
								user.getAbout_me(), user.getStatus(),
								user.getUser_id() }, new int[] { Types.DATE,
								Types.VARCHAR, Types.VARCHAR, Types.INTEGER,
								Types.INTEGER });

		user = isValidUser(user.getEmail(), user.getPassword());
		return user;
	}

	public List<Question> getQuestions() {
		List<Question> qUList = new ArrayList<Question>();
		String sql = "select * from questions";
		qUList = jdbctemplate.query(sql, new QuestionRowMapper());
		return qUList;
	}

	/*
	 * Validates the user
	 */
	public User isValidUser(String email, String password) {
		String sql = "select * from users where email=? and  password=?";

		User user = null;
		try {
			jdbctemplate.queryForObject(sql, new Object[] { email, password },
					new UserRowMapper());

			user = jdbctemplate.queryForObject(sql, new Object[] { email,
					password }, new UserRowMapper());

		} catch (org.springframework.dao.EmptyResultDataAccessException e) {
			return null;
		}
		return user;

	}

	public User authenticate(User user) {

		return isValidUser(user.getEmail(), user.getPassword());

	}

	public User getUserbyId(int id) {
		String sql = "select * from users where user_id=?";

		User user = null;
		try {
			jdbctemplate.queryForObject(sql, new Object[] { id },
					new UserRowMapper());

			user = jdbctemplate.queryForObject(sql, new Object[] { id },
					new UserRowMapper());

		} catch (org.springframework.dao.EmptyResultDataAccessException e) {
			return null;
		}
		return user;

	}

	public String getpassword(String to_address) {
		String sql = "select password from users where email=?";

		try {
			String passString = jdbctemplate.queryForObject(sql,
					new Object[] { to_address }, String.class);
			return passString;
		} catch (org.springframework.dao.EmptyResultDataAccessException e) {
			return null;
		}
	}

	public List<User> getUsers() {
		List<User> userList = new ArrayList<User>();
		String sql = "select * from users";

		userList = jdbctemplate.query(sql, new UserRowMapper());

		return userList;
	}

	public List<User> getMatchedUser(String userName) {
		List<User> userList = new ArrayList<User>();
		String sql = "select * from users where name like '%" + userName
				+ "%';";

		userList = jdbctemplate.query(sql, new UserRowMapper());
		return userList;
	}

	public User getUserByQId(int userId) {
		User user = null;
		String sql = "select * from users where user_id=" + userId;
		user = jdbctemplate.queryForObject(sql, new UserRowMapper());
		return user;
	}

	public User getUserByAId(int userId) {
		User user = null;
		String sql = "select * from users where user_id=" + userId;
		user = jdbctemplate.queryForObject(sql, new UserRowMapper());
		return user;
	}

	public void insertRating(int rating, int userId) {
		String sql = "update users set rating=" + rating + " where user_id="
				+ userId;
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		jdbcTemplate.update(sql);
	}

}
